<template>
  <BaseDialog
    :title="(!props.item.materialId ? '新增' : '编辑') + '素材'"
    :handleCancel="handleCancel"
    :dialogVisible="props.dialogVisible"
  >
    <BaseForm
      labelWidth="100px"
      type="rule"
      :handleOk="handleOk"
      :handleCancel="handleCancel"
      :items="formItems"
      v-model:form="ruleForm"
      :rules="rules"
      :refresh="handleSearch"
    >
      <template #desc>
        <el-form-item label="文件" prop="fileSaveDtoList">
          <NewUpload v-model:files="ruleForm.fileSaveDtoList">
            <template #tip>
              <div class="el-upload__tip">支持扩展名：jpg/png/pdf/doc/docx，文件不能超过10mb</div>
            </template>
            <div class="files" v-for="(item, i) in ruleForm.fileSaveDtoList" :key="i">
              <div class="name">{{ item.name }}</div>
              <span style="color: #1abc9c; cursor: pointer" v-if="item.fileId">
                <span v-if="getFileType(item.url)" style="margin: 0 4px" @click="handleSee(item.url)" class="link">
                  查看
                </span>
                <span style="margin: 0 4px" @click="downloadFile(item)" class="link"> 下载 </span>
              </span>
              <span style="color: #f56c6c; cursor: pointer; margin: 0 4px">
                <span @click="deleteFile(item)" class="link"> 删除 </span>
              </span>
            </div>
          </NewUpload>
        </el-form-item>
      </template>
    </BaseForm>
  </BaseDialog>
  <FilesDetail v-if="fielsVisible" v-model:dialogVisible="fielsVisible" :url="fileUrl"></FilesDetail>
</template>

<script setup lang="ts">
import FilesDetail from '@/components/filesDetals.vue';
import { libraryService } from '@/api/library';
import { download } from '@/hooks/downLoad';
import openMsgBox from '@/hooks/messageBox.js';
import store from '@/store';
const cateList = computed(() => store.getters.cateList);
const props = defineProps({
  dialogVisible: {
    type: Boolean,
  },
  item: {
    type: Object,
  },
  handleSearch: {
    type: Function,
  },
  searchParams: {
    type: Object,
  },
});
const emit = defineEmits(['update:dialogVisible']);

const formItems = ref([
  {
    name: '所属分类',
    key: 'type',
    type: 'select',
    options: cateList,
  },
  {
    name: '素材名称',
    key: 'materialName',
    type: 'input',
    maxlength: '20',
    placeholder: '请输入素材名称',
  },
  {
    name: '内容',
    key: 'content',
    type: 'textarea',
    maxlength: '2000',
    'show-word-limit': true,
  },

  {
    name: '状态',
    key: 'isDisable',
    type: 'switch',
    activeValue: 0,
    inactiveValue: 1,
  },
]);
const rules = reactive({
  type: [{ required: true, message: '请选择', trigger: 'change' }],
  materialName: [{ required: true, message: '请输入', trigger: 'change' }],
  answer: [{ required: true, message: '请输入', trigger: 'change' }],
  isDisable: [{ required: true, message: '请选择', trigger: 'change' }],
});
const ruleForm = ref({
  materialId: '',
  type: '',
  materialName: '',
  fileSaveDtoList: [],
  content: '',
  isDisable: 0,
});
const handleOk = () => {
  if (props.item.materialId) {
    return libraryService.update({
      data: {
        ...ruleForm.value,
        fileSaveDtoList: ruleForm.value.fileSaveDtoList?.map((n) => {
          return {
            fileName: n.name,
            fileUrl: n.url,
            fileId: n.fileId,
          };
        }),
      },
    });
  } else {
    return libraryService.add({
      data: {
        ...ruleForm.value,
        fileSaveDtoList: ruleForm.value.fileSaveDtoList?.map((n) => {
          return {
            fileName: n.name,
            fileUrl: n.url,
            fileId: n.fileId,
          };
        }),
      },
    });
  }
};
const fielsVisible = ref(false);

const fileUrl = ref('');

const handleCancel = () => {
  emit('update:dialogVisible', false);
};
const getFileType = (url) => {
  const arr = url.split('.');
  const type = arr[arr.length - 1];

  if (type == 'jpg' || type == 'png') {
    return true;
  }
  return false;
};
const downloadFile = (item) => {
  const url = item.url || item.fileUrl;
  const name = item.name || item.fileName;
  download({ url, name });
};
const deleteFile = (item) => {
  openMsgBox(
    {
      tips: `是否确定删除该文件?`,
    },
    () => {
      ruleForm.value.fileSaveDtoList.splice(ruleForm.value.fileSaveDtoList.indexOf(item), 1);
    },
    () => {},
  );
};
const page = reactive({
  pageSize: 10,
  currentPage: 1,
  total: 0,
});
const handleSee = (url) => {
  fielsVisible.value = true;
  console.log(url);
  fileUrl.value = url;
};
onMounted(() => {
  if (props.item.materialId) {
    ruleForm.value.materialId = props.item.materialId;
    ruleForm.value.materialName = props.item.materialName;
    ruleForm.value.type = props.item.type;
    ruleForm.value.isDisable = props.item.isDisable;
    ruleForm.value.content = props.item.content;
    ruleForm.value.fileSaveDtoList = props.item.fileDtoList?.map((n) => {
      return {
        name: n.fileName,
        url: n.fileUrl,
        fileId: n.fileId,
      };
    });
  } else {
    ruleForm.value.type = props.searchParams.type;
  }
});
</script>

<style lang="scss" scoped>
.files {
  display: flex;
  font-size: 12px;

  .name {
    flex: 1;
    width: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>
